import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter_plugin/base/controller/base_controller.dart';
import 'package:flutter_plugin/util/log_util.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../constant/env.dart';
import '../../ext/get_extension.dart';
import '../../net/api_respository.dart';
import '../../net/http_url.dart';
import '../../res/colors.dart';
import '../../res/style.dart';
import '../../res/text_style.dart';
import '../../routes/router_util.dart';
import '../../util/aes_utils.dart';
import '../../util/string_util.dart';
import 'login_state.dart';

class LoginLogic extends BaseController<LoginLogic> {
  final LoginState state = LoginState();

  @override
  void loadNet() {
    // TODO: implement loadNet
  }

  @override
  void onInit() {
    super.onInit();

  }

  void privacyCheck(String phone) async {
    if (!StringUtil.isPhone(phone)) {
      state.isPhoneError.value = true;
      return;
    }

    if (state.privacyCheck.value) {
      sendLoginCode(phone);
    } else {
      GetExtension.showCommonDialog(
        title: "使用前须同意",
        negaText: "不同意",
        posiText: "同意并继续",
        centerWidget: Column(
          children: [
            RichText(
              textAlign: TextAlign.center,
              text: TextSpan(
                style: TextStyle(
                  fontWeight: FontWeight.w400,
                  fontSize: 16.sp,
                ),
                children: [
                  // 为了保障您的合法权益，请阅读并同意
                  TextSpan(
                    text: "为了保障您的合法权益，请阅读并同意",
                    style: Styles.style_FF666666,
                  ),
                  TextSpan(
                      text: "《用户协议》",
                      style: Styles.style_FF00A1FF,
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          RouterUtil.toWebPage("用户协议", Env.envConfig.userAgreementUrl);
                        }),
                  TextSpan(
                    text: "和",
                    style: Styles.style_FF666666,
                  ),
                  TextSpan(
                      text: "《隐私协议》",
                      style: Styles.style_FF00A1FF,
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          RouterUtil.toWebPage("隐私声明 ", Env.envConfig.privacyPolicyUrl);
                        }),
                ],
              ),
            ),
            Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(top: 13.h),
              child: Text(
                "臻情守护家人将严格保护你的个人信息安全",
                textAlign: TextAlign.center,
                style: TextStyles.textStyle(ColorStyle.color_FF303030, 14.sp, fontWeight: FontWeight.w600),
              ),
            ),
          ],
        ),
        posiTap: () {
          state.privacyCheck.value = true;
          debugPrint("============posiTap");
          sendLoginCode(phone);
        },
        negaTap: () {
          state.privacyCheck.value = false;
          debugPrint("============posiTap");
        },
      );
    }
  }

  void sendLoginCode(String phone) {
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    var queryParameters = <String, dynamic>{};
    queryParameters['phone'] = AesUtils.encryptAes(plainText: phone);
    ApiRepository.instance.request<String>(HttpUrl.sendLoginCode,
        params: queryParameters, withLoading: true, loadText: '获取验证码中…', success: (it) {
      LogD("sendLoginCode $it");
      RouterUtil.toLoginSmsCodePage(phone);
    }, error: (e) {
      LogD("sendLoginCode err ${e.code} ${e.message}");
      if (e.code == "204") {
        GetExtension.showCommonDialog(
          content: "您是“臻情守护关爱端”用户，请注销“关爱端”账户后再来注册",
          negaVisible: false,
          posiText: "确定",
          posiTap: () {},
        );
      } else if (e.code == "111") {
        showToast("验证码发送频繁，请稍后再试");
      } else {
        showToast(e.message ?? "获取验证码失败");
      }
    });
  }
}
